import dgo.SimpleInput;
import javax.microedition.lcdui.game.*;
import game.scene.*;
import starruby.*;
import java.util.Hashtable;

class MainCanvas extends GameCanvas 
    implements Runnable {

    private SceneStack _sceneStack;
    private Texture _screen;

    MainCanvas() {
      super(false);
      _screen = new Texture(getGraphics(), 240, 240);
      _sceneStack = new SceneStack(new game.scene.title.Scene(new game.GlobalModel(_screen)));
    }

    /*--------------------------------------------------------------------------
      This application uses simple state machine for managing scenes.
      _sceneStack is a stack of scenes.
      Here I am making game by rendering on _screen.
     -------------------------------------------------------------------------*/
    public void run() {
        long sleepTime = 0L;
        while (true) {
          SimpleInput.update(this);

          game.scene.BaseScene s = _sceneStack.current();

          _screen.fill(0, 0, 0);
          if(s != null){
            s.update(_sceneStack);
            s.render(_screen);
            s = null;
          }else{
            //quit game
          }
          flushGraphics();
          sleepTime = keepFPS(sleepTime);
          //Runtime.getRuntime().gc();
          
          //Show memory left
          //System.out.println(Runtime.getRuntime().freeMemory() + " / " + Runtime.getRuntime().totalMemory());
        }
    }

    /*---------------------
      Keep the FPS constant.
     ---------------------*/
    private long keepFPS(long sleepTime){
      while(
        System.currentTimeMillis()<sleepTime + 30 && 
        System.currentTimeMillis()-sleepTime < 30
      ){}
      return System.currentTimeMillis();
    }
}